<template>
    <el-row style="margin-top: 15px;">
        <el-col :span="12">
            <el-image src="/src/assets/ad.png" />
        </el-col>
        <el-col :span="12">
            <el-form class="loginForm">
                <h1>用户登录</h1>
                <el-form-item>
                    <el-input prefix-icon="User" placeholder="请输入用户名" v-model="loginInfoDTO.name"/>
                </el-form-item>
                <el-form-item>
                    <el-input type="password" prefix-icon="Key" placeholder="请输入密码" v-model="loginInfoDTO.password"/>
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 175px; margin-right: 5px;" prefix-icon="Picture" placeholder="请输入验证码" v-model="loginInfoDTO.captcha" />
                    <img width="160px" :src="captcha" @click="loadCaptcha" alt="验证码"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="loginBtn" @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script setup>
import userApi from "@/api/userApi.js";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";
import captchaApi from "@/api/captcha.js";

const tokenStore = useTokenStore();
const userStore = useUserStore();
const router = useRouter();
//保存验证码
const imageBase64Data = ref(null);
//用户注册信息
//定义数据模型
const loginInfoDTO = ref({
    name: '',
    password: '',
    captcha: '',
    uuid: ''
})

//获取验证码
const captcha = ref('')
function loadCaptcha() {
    captchaApi.captcha().then(result => {
        captcha.value = result.data.captcha
        loginInfoDTO.value.uuid = result.data.uuid
    })
}

loadCaptcha()

//用户登录
function login() {
    userApi.login(loginInfoDTO.value).then(result => {
        ElMessage.success(result.msg);
        //保存token
        tokenStore.updateToken(result.data);
        //获取用户信息
        getInfo();
        //跳转到前台首页
        router.push("/index");
    });
}

//获取用户信息
function getInfo() {
    userApi.userInfo().then(result => {
        //将已登录用户信息保存在Pinia中
        userStore.updateUser(result.data);
    });
}

</script>

<style scoped>
.loginForm {
    width: 300px;
    margin: 25px 150px;
}

.loginForm h1 {
    text-align: center;
    margin-bottom: 20px;
}

.loginBtn {
    width: 100%;
}
</style>